<template>
	<div>
		<h1>图片列表</h1>
		<el-button @click="onAddClick">新建</el-button>
		<div class="img-container">
			<ul v-for="item in list" :key="item.url">
				<li>
					<img :src="item.url" alt="" />
				</li>
			</ul>
		</div>
		<el-pagination
			@current-change="onChange"
			background
			layout="prev, pager, next"
			:total="opt.total"
		>
		</el-pagination>
		<el-drawer
			title="我是标题"
			:visible.sync="drawer"
			direction="rtl"
			:before-close="handleClose"
		>
			<el-form :model="formList">
				<el-form-item label="名称">
					<el-input v-model="formList.imgName" required></el-input>
				</el-form-item>
				<el-form-item label="描述">
					<el-input type="textarea" v-model="formList.desc"></el-input>
				</el-form-item>
				<el-form-item>
					<input type="file" @change="imgOnChange" multiple />
				</el-form-item>
				<el-form-item>
					<el-button @click="onCloseClick">取消</el-button>
					<el-button @click="uploadImgfn">创建</el-button>
				</el-form-item>
			</el-form>
		</el-drawer>
	</div>
</template>

<script>
import axios from 'axios'
import Cookie from 'js-cookie'
import { debounce, throttle } from 'lodash'
export default {
	data() {
		return {
			list: [],
			opt: { page: 1, size: 8, total: 0 },
			drawer: false,
			file: '',
			uploadImgfn: null,
			formList: {
				imgName: '',
				desc: ''
			}
		}
	},
	created() {
		this.getList()
	},
	mounted() {
		// 防抖优化添加函数
		this.uploadImgfn = debounce(this.onCreateClick, 500)
	},
	methods: {
		onCloseClick() {
			this.drawer = false
		},
		// 创建的时候，要调用上传图片接口
		async onCreateClick() {
			console.log(this.formList.imgName)
			// const csrfToken = Cookie.get('csrfToken')
			// form data数据格式上传
			const formData = new FormData()
			formData.append('file', this.file)
			const uploadData = await this.$http.post(
				`/api/mouthUpload?imgName=${this.formList.imgName}`,
				formData
			)
			console.log(uploadData, 'uploadData')
		},
		imgOnChange(e) {
			const file = e.target.files[0]
			console.log(file, 'target')
			this.file = file
		},
		onAddClick() {
			this.drawer = true
		},
		handleClose() {
			this.drawer = false
		},
		onChange(page) {
			this.opt.page = page
			this.getList()
		},
		getList() {
			this.$http
				.get('/api/imgArr', {
					params: { page: this.opt.page, size: this.opt.size }
				})
				.then((res) => {
					console.log('res:', res)
					this.list = res.data
					this.opt.total = res.total
				})
		}
	}
}
</script>

<style lang="scss">
.img-container {
	width: 100%;
	display: flex;
	flex-wrap: wrap;
	ul {
		width: 150px;
		height: 150px;
		padding: 5px;
		border: 1px solid #ccc;
		margin: 5px;
		img {
			width: 100%;
			height: 100%;
		}
	}
}
</style>
